<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class SetController extends Controller
{
    public function index(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'     => 'required|integer|min:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        //处理
        $user_id  = $input["user_id"];

        //查找用户相关的通知集
        $setUserResult = DB::select("SELECT im_set_user.set_id,
            im_set_user.is_replied,im_set_user.is_viewed,im_set_user.is_latest,
            im_inform.id AS inform_id,im_inform.title AS inform_title,im_inform.send_time AS time,im_inform.is_closed,
            im_set.name AS set_name,im_set.icon AS set_icon
            FROM im_set_user
            INNER JOIN im_inform ON im_inform.id = im_set_user.inform_id
            INNER JOIN im_set ON im_set.id = im_set_user.set_id
            WHERE im_set_user.user_id = $user_id
            AND im_set.is_deleted = false
            ORDER BY im_set_user.created_at DESC 
            ");

        //聚合未回复数
        $setUserUnrepliedCount = [];
        foreach ($setUserResult as $value) {
            //$count = ($value->is_replied || ($value->is_closed && $value->is_viewed))?0:1;
            $count = $value->is_viewed?0:1;
            if(!isset($setUserUnrepliedCount[$value->set_id])){
                $setUserUnrepliedCount[$value->set_id] = $count;
            }else{
                $setUserUnrepliedCount[$value->set_id] += $count;
            }
        }

        //构造返回数据   
        $setUserReturn = [];
        foreach ($setUserResult as $value) {
            if($value->is_latest){
                unset($value->is_latest,$value->is_replied);
                $value->unreplied_count = $setUserUnrepliedCount[$value->set_id];
                $setUserReturn[] = $value;
            }
        }
        return $this::jsonResponse(false,$setUserReturn);
    }

    public function show($id)
    {
        //$response = API::post('http://192.168.2.103:9910/api/set', [], ["app_id"=>1,"icon"=>"123","name"=>"test"]);
        //return (array)$response->body;
        //$pheanstalk = new Pheanstalk('192.168.2.103');

        // ----------------------------------------
        // producer (queues jobs)
        //  for ($i=0; $i < 1000; $i++) {
        // $data = ["post","http://192.168.2.103:9910/api/set",["app_id"=>1,"icon"=>"123","name"=>"test"]];
        // $pheanstalk
        //    ->useTube('restapi')
        //    ->put(json_encode($data),0,0);
        //  }


        // ----------------------------------------
        // worker (performs jobs)

        // $job = $pheanstalk
        //   ->watch('testtube')
        //   ->ignore('default')
        //   ->reserve();

        // echo $job->getData();

        // $pheanstalk->delete($job);

        // ----------------------------------------
        // check server availability

        //echo $pheanstalk->getConnection()->isServiceListening(); // true or false
    }

    public function showIdByObject(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'    => 'required|integer|min:1',
                'object'    => 'required|string|min:2',
                'object_id' => 'required|string|min:1',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $setId = DB::table("im_set")
            ->where("app_id",$input["app_id"])
            ->where("object",$input["object"])
            ->where("object_id",$input["object_id"])
            ->value("id");

        return $this::jsonResponse(false,$setId);
    }

    public function store(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'    => 'required|integer|min:1',
                'name'      => 'required|string|min:2',
                'icon'      => 'required|string|min:2',
                'object'    => 'string|min:2',
                'object_id' => 'string|min:1',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        //处理
        $setData = [];
        foreach (["app_id","name","icon","object","object_id"] as $value) {
            if(!empty($input[$value])) $setData[$value] = $input[$value];
        }

        $setId = DB::table("im_set")->insertGetId($setData);

        return $this::jsonResponse(false,$setId);
    }

    public function update(Request $request, $id)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'name'      => 'string|min:2',
                'icon'      => 'string|min:2',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        //处理
        $setData = [];
        foreach (["name","icon"] as $value) {
            if(!empty($input[$value])) $setData[$value] = $input[$value];
        }
        
        if(empty($setData))
            return $this::jsonResponse(true,"","UpdateDataEmpty");

        $setUpdateResult = DB::table("im_set")->where("id",$id)->update($setData);

        return $this::jsonResponse(false,$setUpdateResult);
    }

    public function destroy($id)
    {
        DB::beginTransaction();

        DB::table("im_set")->where("id",$id)->update(["is_deleted"=>true]);
        DB::table("im_set_user")->where("set_id",$id)->delete();

        $informCloseData = [
            "is_closed"  =>true,
            "close_time" =>date("Y-m-d H:i:s")
        ];

        $informCloseResult = DB::table("im_inform")->where("set_id",$id)->update($informCloseData);
        
        DB::commit();

        return $this::jsonResponse(false,true);
    }

    public function destroyUser($setId,$userId)
    {
        $setUserResult = DB::table("im_set_user")->where("set_id",$setId)->where("user_id",$userId)->delete();

        return $this::jsonResponse(false,$setUserResult);
    }

}
